var t = getApp();
const timer= require('../../utils/timer.js');
Page({
    data: {
        prefix: "https://cdn.kaayun.com/",
        vote_type: "",
        date_end: "",
        thight:50,
        time_end: "",
        userInfo: {},
        canIUse: wx.canIUse("button.open-type.getUserInfo"),
        hasUserInfo: !1,
        submiting: !1,
        helper_switch: {
            graphic: !1,
            daily: !1,
            share: !1,
            multiple: !1,
            anonymous: !0,
            profile: !1,
            view: !0
        },
        helper_multiple: {
            least: 1,
            most: 2
        },
        helper_top: {
            title: "",
            description: ""
        },
        helper_opts: {
            opts: [ {
                fid: "",
                value: "",
                num:0,
                key: "unique_0"
            }, {
                fid: "",
                value: "",
                num:0,
                key: "unique_1"
            } ],
            unique_helper: 2
        },
        templateSettingIndex: 0,
        templateSettings: [ {
            title: "显示票数"
        }, {
            title: "显示票数和明细"
        }, {
            title: "不显示票数"
        } ],
        description: "",
        checkboxValues: [  ],
        checkboxItems: [ ]
    },
    onLoad: function(e) {
        var a = this;
        this.initDate(e);
        var o = "创建活动投票";
        "PK" === e.vote_type && (o = "创建二选一投票"), wx.setNavigationBarTitle({
            title: o
        }), t.globalData.userInfo ? this.setData({
            userInfo: t.globalData.userInfo,
            hasUserInfo: !0
        }) : this.data.canIUse ? t.userInfoReadyCallback = function(e) {
            a.setData({
                userInfo: e.userInfo,
                hasUserInfo: !0
            });
        } : wx.getUserInfo({
            success: function(e) {
                t.getEditUserInfo(e.userInfo, function() {
                    t.globalData.userInfo = e.userInfo, a.setData({
                        userInfo: e.userInfo,
                        hasUserInfo: !0
                    });
                });
            }
        });
    },
    desChange: function(e) {
      
        if(e.detail.value.length>30){
            this.setData({
                thight:100
            })
        if(e.detail.value.length>60){
            this.setData({
                thight:120
            })
        }
        if(e.detail.value.length>100){
            this.setData({
                thight:250
            })
        }
        }
        this.data.description = e.detail.value;
    },
  
    inputChange: function(t) {
        var info=t.currentTarget.dataset.index
        var res= (0, this.myDefault)({}, "helper_opts.opts[".concat(t.currentTarget.dataset.index, "].value"), t.detail.value);
      
        var newinfo="helper_opts.opts["+t.currentTarget.dataset.index+"].value"
        this.setData({
            [newinfo]:t.detail.value
        });
    },
    myDefault(obj) {
    return obj && obj.__esModule ? obj : {
        default: obj
    };
},

    newVote(param={}){
        var that=this
  let mycontent=JSON.stringify(param)
    
    wx.Bmob.checkMsg(mycontent).then(res => {

      if(res.msg=='ok'||res.msg=='OK'){
         wx.showLoading({
      title: '添加中...',
    })

wx.Als.bmobFunc('vote_info', 'add', param).then(res => {
      console.log(res)

      wx.hideLoading();
      if(res){
        that.setData({
          title:'',
          content:'',
          pics:[]
        })
        wx.showToast({
          title: '添加成功~',
        })
        that.setData({
            thight:30,
            helper_switch: {
                graphic: !1,
                daily: !1,
                share: !1,
                multiple: !1,
                anonymous: !0,
                profile: !1,
                view: !0
            },
            helper_multiple: {
                least: 1,
                most: 2
            },
            helper_top: {
                title: "",
                description: ""
            },
            helper_opts: {
                opts: [ {
                    fid: "",
                    value: "",
                    num:0,
                    key: "unique_0"
                }, {
                    fid: "",
                    value: "",
                    num:0,
                    key: "unique_1"
                } ],
                unique_helper: 2
            },
        })
        wx.navigateTo({
            url:'detail?tid='+res.objectId
        })

      }
    })

      }

  }).catch(err => {

      wx.showToast({
        title: '发布失败',
        icon:'none'
      })
  })
    },
    bindReplaceInput: function(e) {
        var t = e.detail.value;
        return "0" === t ? "1" : t;
    },
    bindTemplateSettingChange: function(e) {
        this.setData({
            templateSettingIndex: Number(e.detail.value)
        });
    },
    voteAddOpt: function() {
        this.data.helper_opts.opts.length < 100 ? (this.data.helper_opts.opts.push({
            fid: "",
            num:0,
            value: "",
            key: "unique_" + this.data.helper_opts.unique_helper++
        }), this.setData({
            "helper_opts.opts": this.data.helper_opts.opts
        })) : t.showTip("最多可添加100个选项。");

   
    },
    voteDeleteOpt: function(e) {
        this.data.helper_opts.opts.length > 2 ? (this.data.helper_opts.opts.splice(e.currentTarget.dataset.index, 1), 
        this.setData({
            "helper_opts.opts": this.data.helper_opts.opts
        })) : t.showTip("最少2个选项。"), console.error(JSON.stringify(e, null, 5));
    },
    voteUploadImage: function(e) {
        var t = this, a = e.currentTarget.dataset.index;
        this.data.helper_opts.opts[a].fid ? wx.showActionSheet({
            itemList: [ "预览图片", "重新上传" ],
            success: function(e) {
                0 === e.tapIndex && wx.previewImage({
                    urls: [ t.data.prefix + t.data.helper_opts.opts[a].fid ]
                }), 1 === e.tapIndex && t.voteChooseImage(a);
            }
        }) : this.voteChooseImage(a);
    },
    voteChooseImage: function(e) {
        var t = this;
        wx.showActionSheet({
            itemList: [ "拍照", "从手机相册选择"],
            success: function(a) {
                0 === a.tapIndex && t.voteChooseImageNext([ "camera" ], e), 1 === a.tapIndex && t.voteChooseImageNext([ "album" ], e), 
                2 === a.tapIndex && wx.chooseMessageFile({
                    count: 1,
                    type: "image",
                    success: function(a) {

                            
                        // a.tempFiles && a.tempFiles.length > 0 && t.voteChooseImageSuccess(a.tempFiles[0].path, e);
                    }
                });
            }
        });
    },
    voteChooseImageNext: function(e, t) {
        var a = this;
        wx.chooseImage({
            count: 1,
            sizeType: [ "compressed" ],
            sourceType: e,
            success: function(e) {
                a.voteChooseImageSuccess(e.tempFilePaths[0], t);
            },
            fail: function(e) {
                console.error("chooseImage", e);
            }
        });
    },
    voteChooseImageSuccess: function(e, a) {
        var that= this;
      
   

        var file;
        var uid = wx.getStorageSync('uid');
        let day=timer.formatTime(new Date());
        var randname=uid+'_'+day+'_vote.jpg';
        
   
        file = wx.Bmob.File(randname, e);
        file.imgSecCheck().then(res => {
          if(res){
        console.log(res)
        console.error("===00==")
          wx.hideLoading()
      var file2= wx.Bmob.File(randname, e);
            file2.save().then(res=>{
           wx.hideLoading();
     
          that.data.helper_opts.opts[a].url = res[0].url, that.setData({
                                            "helper_opts.opts": that.data.helper_opts.opts,
                                            canadd:true
                                        });
            })

       

       
        }
        }).catch(err=>{
            console.log(err);
            wx.hideLoading()
            that.setData({
              canadd:true
            })
            wx.showToast({
              title:'图片违规',
              icon:'none'
            })
        })

        // setTimeout(function() {
        //     wx.showLoading({
        //         title: "上传中...",
        //         mask: !0,
        //         success: function(s) {
        //             wx.uploadFile({
        //                 url: "https://api.kaayun.com/wx/v1/upload",
        //                 filePath: e,
        //                 name: "file",
        //                 formData: {
        //                     source: "miniprogram_group-vote"
        //                 },
        //                 success: function(e) {
        //                     if (console.error("Upload", e), wx.hideLoading(), 200 === e.statusCode) {
        //                         try {
        //                             e.data = JSON.parse(e.data);
        //                         } catch (e) {
        //                             return t.showTip("上传图片失败。");
        //                         }
        //                         switch (e.data.commands.statusCode) {
        //                           case "SUCCESS":
        //                             o.data.helper_opts.opts[a].fid = e.data.payload.uploadResponse.fid, o.setData({
        //                                 "helper_opts.opts": o.data.helper_opts.opts
        //                             });
        //                             break;

        //                           case "SIZE":
        //                             t.showTip("超过图片大小限制：1M");
        //                             break;

        //                           case "ERROR_RISKY":
        //                             t.showTip("图片包含违规内容（色情、涉政等）");
        //                             break;

        //                           default:
        //                             t.showTip("上传图片失败。");
        //                         }
        //                     } else t.showTip("上传图片失败。");
        //                 },
        //                 fail: function(e) {
        //                     console.error(e), wx.hideLoading(), t.showTip("上传图片失败。");
        //                 }
        //             });
        //         },
        //         fail: function(e) {}
        //     });
        // }, 500);
    },
    profileChange: function(e) {
        this.setData({
            "helper_switch.profile": e.detail.value
        });
    },
    dailyChange: function(e) {
        this.setData({
            "helper_switch.daily": e.detail.value
        });
    },
    multipleChange: function(e) {
        this.setData({
            "helper_switch.multiple": e.detail.value
        });
    },
    shareChange: function(e) {
        this.setData({
            "helper_switch.share": !e.detail.value
        });
    },
    graphicChange: function(e) {
    
        this.setData({
            "helper_switch.graphic": e.detail.value
        });
    },
    anonymousChange: function(e) {
        this.setData({
            "helper_switch.anonymous": e.detail.value
        });
    },
    checkboxChange: function(e) {
        for (var a = this.data.checkboxItems, o = e.detail.value, s = [], i = 0, n = a.length; i < n; ++i) {
            a[i].checked = !1;
            for (var l = 0, r = o.length; l < r && l < 3; ++l) if (a[i].value == o[l]) {
                s.push(o[l]), a[i].checked = !0;
                break;
            }
        }
        this.setData({
            checkboxValues: s,
            checkboxItems: a
        }), e.detail.value.length > 3 && t.showTip("最多可加三项信息。");
    },
    onGetUserInfo: function(e) {
        var a = this;
        e.detail.userInfo && t.getEditUserInfo(e.detail.userInfo, function() {
            t.globalData.userInfo = e.detail.userInfo, a.setData({
                userInfo: e.detail.userInfo,
                hasUserInfo: !0
            });
        });
    },
    initDate: function(e) {
        var a = new Date(), o = new Date(a);
        o.setDate(a.getDate() + 1);
        var s = this.initFormatDate(o), i = {};
        if (i.date_end = s.date, i.time_end = s.time, e.copy && t.globalData.formInfo) {
            i.helper_switch = t.globalData.formInfo.helper_switch, i.helper_top = t.globalData.formInfo.helper_top, 
            i.helper_opts = t.globalData.formInfo.helper_opts, i.helper_multiple = t.globalData.formInfo.helper_multiple, 
            i.description = t.globalData.formInfo.helper_top.description, i.templateSettingIndex = t.globalData.formInfo.templateSettingIndex;
            var n = t.globalData.formInfo.checkboxValues;
            if (n && n.length > 0) {
                for (var l = this.data.checkboxItems, r = 0, h = l.length; r < h; ++r) {
                    l[r].checked = !1;
                    for (var u = 0, p = n.length; u < p && u < 3; ++u) if (l[r].value === n[u]) {
                        l[r].checked = !0;
                        break;
                    }
                }
                i.checkboxValues = n, i.checkboxItems = l;
            }
            t.globalData.formInfo = null;
        }
        e.vote_type && (i.vote_type = e.vote_type, "PK" === i.vote_type && (i.templateSettings = [ {
            title: "显示票数"
        }, {
            title: "显示票数和明细"
        } ])), this.setData(i);
    },
    initFormatDate: function(e) {
        var t = e.getFullYear(), a = e.getMonth() + 1, o = e.getDate(), s = e.getHours(), i = e.getMinutes();
        return a < 10 && (a = "0" + a), o < 10 && (o = "0" + o), s < 10 && (s = "0" + s), 
        i < 10 && (i = "0" + i), {
            date: t + "-" + a + "-" + o,
            time: s + ":" + i
        };
    },
    bindDateEndChange: function(e) {
        this.setData({
            date_end: e.detail.value
        });
    },
    bindTimeEndChange: function(e) {
        this.setData({
            time_end: e.detail.value
        });
    },
    formSubmit: function(e) {
        var a = this, o = e.detail.value;
        var uid=wx.getStorageSync('uid');
        if(!uid){
            wx.showToast({
                title:'请登录',
                icon:'none'
            })
            return;
        }
        var helper_opts=a.data.helper_opts
        if (console.error("formSubmit>>>", e), !o.title) return t.showTip("请先输入投票标题。");
        o.description = this.data.description;
        for (var s = 0; s < this.data.helper_opts.opts.length; s++) if ( 
        !helper_opts.opts[s].value) return t.showTip("第".concat(s + 1, "个选项无有效内容。"));
        if (this.data.helper_switch.graphic) for (var i = 0; i < this.data.helper_opts.opts.length; i++) if (!this.data.helper_opts.opts[i].url) return t.showTip("第".concat(i + 1, "个选项无图片。"));
        if (this.data.helper_switch.multiple) {
            if (o.least = Number(o.least) || 0, o.most = Number(o.most) || 0, o.least < 1) return t.showTip("最少可选项数不能小于 1");
            if (o.least > o.most) return t.showTip("最少可选项数不能超过最多可选项数。");
            if (o.most > this.data.helper_opts.opts.length) return t.showTip("最多可选项数不能超过总选项数。");
            if (o.most <= 1) return t.showTip("最多可选项数必须大于 1。");
        }
        0 === this.data.templateSettingIndex && (o.view = !0), 1 === this.data.templateSettingIndex && (o.view = !0, 
        o.view_record = !0), o.checkboxValues = this.data.checkboxValues, wx.showModal({
            title: "温馨提示",
            cancelText: "取消",
            confirmText: "确定",
            content: "投票创建后不支持再次修改，请确认无误后提交。",
            success: function(e) {
          
            
               o.all=a.data.helper_opts.opts.length;
               o.votearr=a.data.helper_opts
          
               a.formSubmitNext(o);
                // e.confirm && (a.setData({
                //     submiting: !0
                // }), t.requestSubscribeMessage(function(e) {
                //     e || (o.tmplIds = t.globalData.tmplIds), a.formSubmitNext(o);
                // }));
            }
        });
    },
    formSubmitNext: function(e) {
        for (var a = this, o = [], s = 0; s < this.data.helper_opts.opts.length; s++) o.push(this.data.helper_opts.opts[s].fid);
    
        var uid=wx.getStorageSync('uid')
        var uimg=wx.getStorageSync('uimg')
        var nickName=wx.getStorageSync("nickName")
        const pointer = wx.Bmob.Pointer('vote_user')
        const relID = pointer.set(uid)
        console.log(o);
        var param={
                form: e,
                uid:uid,
                user_id:relID,
                uimg:uimg,
                nickName:nickName,
                group_count:0,
                vote_type: 2,
                user_info: {}
        }
        this.newVote(param)
    
       
    },
    onReady: function() {},
    onShow: function() {},
    onHide: function() {},
    onUnload: function() {},
    onPullDownRefresh: function() {},
    onReachBottom: function() {},
    onShareAppMessage: function() {
          return {
            title: "快来投票吧",
            path: "/pages/index/index"
        };
    }
});